{% extends 'base.html' %}

<!-- 重写页面标题 -->
{% block title %}工时利用率 - 工时工具{% endblock %}

<!-- 填充页面主要内容 -->
{% block content %}
    <!-- 页面标题 -->
    <div class="text-center mb-8">
        <h1 class="text-[clamp(1.8rem,3vw,2.5rem)] font-bold text-gray-800 mb-2">工时利用率计算工具</h1>
        <p class="text-gray-600 text-lg">上传数据文件，计算工作效率百分比</p>
    </div>

    <!-- 主要内容区域 -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- 左侧表单卡片 -->
        <div class="lg:col-span-2">
            <div class="card h-full flex flex-col">
                <h2 class="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                    <i class="fa fa-file-text-o mr-2 text-primary"></i>数据上传与设置
                </h2>

                <form id="efficiencyForm" class="space-y-10 flex-grow">
                    <!-- 文件上传区域 -->
                    <div class="space-y-3 flex-grow flex flex-col">
                        <label for="file" class="block text-sm font-medium text-gray-700">
                            <i class="fa fa-upload mr-1"></i>上传数据文件
                        </label>
                        <div class="relative flex-grow flex flex-col">
                            <div class="flex items-center justify-center w-full flex-grow">
                                <label for="file" class="flex flex-col items-center justify-center w-full h-full border-2 border-dashed border-gray-300 rounded-lg cursor-pointer bg-gray-50 hover:bg-gray-100 transition-all duration-300">
                                    <div class="flex flex-col items-center justify-center pt-5 pb-6">
                                        <i class="fa fa-cloud-upload text-3xl text-gray-400 mb-2"></i>
                                        <p class="mb-2 text-sm text-gray-500"><span class="font-medium">点击上传文件</span> 或拖放至此</p>
                                        <p class="text-xs text-gray-500">支持 CSV 或 XLSX 文件</p>
                                    </div>
                                    <input id="file" type="file" class="hidden" accept=".csv,.xlsx" required="">
                                </label>
                            </div>
                            <!-- 文件信息展示区域 -->
                            <div id="file-info-container" class="mt-3 hidden">
                                <div class="file-info">
                                    <i id="file-icon" class="fa fa-file-text-o text-primary text-xl mr-3"></i>
                                    <p id="file-name" class="flex-grow text-sm text-gray-600 truncate">LvSonglin-1753751116157.csv (0.54 MB)</p>
                                    <button type="button" id="delete-file" class="text-gray-400 hover:text-danger transition-colors duration-300 ml-2">
                                        <i class="fa fa-trash-o text-lg"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 工时输入区域 -->
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div class="space-y-2">
                            <label for="regularHours" class="block text-sm font-medium text-gray-700">
                                <i class="fa fa-clock-o mr-1"></i>常班 (小时)
                            </label>
                            <input type="number" id="regularHours" name="regularHours" step="0.5" min="0" class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus transition-all duration-300" placeholder="输入常班工时" required="">
                        </div>

                        <div class="space-y-2">
                            <label for="overtimeHours" class="block text-sm font-medium text-gray-700">
                                <i class="fa fa-calendar-plus-o mr-1"></i>加班 (小时)
                            </label>
                            <input type="number" id="overtimeHours" name="overtimeHours" step="0.5" min="0" class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus transition-all duration-300" placeholder="输入加班工时" required="">
                        </div>

                        <div class="space-y-2">
                            <label for="nonProductionHours" class="block text-sm font-medium text-gray-700">
                                <i class="fa fa-coffee mr-1"></i>非产 (小时)
                            </label>
                            <input type="number" id="nonProductionHours" name="nonProductionHours" step="0.5" min="0" class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus transition-all duration-300" placeholder="输入非产工时" required="">
                        </div>
                    </div>

                    <!-- 提交按钮 -->
                    <div class="pt-2">
                        <button type="submit" id="submitBtn" class="btn-primary w-full flex items-center justify-center">
                            <i class="fa fa-calculator mr-2"></i>计算效率
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- 右侧仪表盘卡片 -->
        <div class="lg:col-span-1">
            <div class="dashboard-card h-full flex flex-col">
                <h2 class="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                    <i class="fa fa-tachometer mr-2 text-primary"></i>效率仪表盘
                </h2>

                <div class="flex-grow flex flex-col items-center justify-center">
                    <!-- 仪表盘带中间文本 -->
                    <div class="relative w-64 h-64 mb-6">
                        <canvas id="efficiencyChart"></canvas>
                        <!-- 中间百分比文本 -->
                        <div class="absolute inset-0 flex flex-col items-center justify-center">
                            <p id="efficiencyPercentage" class="text-3xl font-bold text-gray-800">-</p>
                            <p class="text-xs text-gray-500">工作效率</p>
                        </div>
                    </div>

                    <!-- 详细数据展示 -->
                    <div class="w-full grid grid-cols-2 gap-3 mt-2">
                        <div class="bg-gray-50 p-3 rounded-lg">
                            <p class="text-xs text-gray-500">实际工作时长</p>
                            <p id="qualifiedHours" class="text-lg font-semibold text-gray-800">-</p>
                        </div>
                        <div class="bg-gray-50 p-3 rounded-lg">
                            <p class="text-xs text-gray-500">有产出的工时</p>
                            <p id="totalHours" class="text-lg font-semibold text-gray-800">-</p>
                        </div>
                        <div class="bg-gray-50 p-3 rounded-lg">
                            <p class="text-xs text-gray-500">总工作时长</p>
                            <p id="totalWorkingHours" class="text-lg font-semibold text-gray-800">-</p>
                        </div>
                        <div class="bg-gray-50 p-3 rounded-lg">
                            <p class="text-xs text-gray-500">帧数</p>
                            <p id="frameRate" class="text-lg font-semibold text-gray-800">-</p>
                        </div>
                        <div class="bg-gray-50 p-3 rounded-lg col-span-2">
                            <p class="text-xs text-gray-500">总元素量</p>
                            <p id="totalElement" class="text-lg font-semibold text-gray-800">-</p>
                        </div>
                    </div>
                </div>

                <!-- 颜色说明 -->
                <div class="mt-6 grid grid-cols-3 gap-2 text-xs">
                    <div class="flex items-center">
                        <span class="inline-block w-3 h-3 rounded-full bg-danger mr-1"></span>
                        <span class="text-gray-600">低于75%</span>
                    </div>
                    <div class="flex items-center">
                        <span class="inline-block w-3 h-3 rounded-full bg-warning mr-1"></span>
                        <span class="text-gray-600">75%-85%</span>
                    </div>
                    <div class="flex items-center">
                        <span class="inline-block w-3 h-3 rounded-full bg-success mr-1"></span>
                        <span class="text-gray-600">高于85%</span>
                    </div>
                </div>
            </div>
        </div>
    </div>


    <!-- 确认对话框（子页面共用） -->
    <div id="confirmDialog" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg shadow-xl p-6 max-w-md w-full mx-4 transform transition-all duration-300 scale-95 opacity-0" id="dialogContent">
            <div class="text-center">
                <div class="inline-flex items-center justify-center w-12 h-12 rounded-full bg-primary/10 text-primary mb-4">
                    <i class="fa fa-info-circle text-xl"></i>
                </div>
                <h3 class="text-lg font-medium text-gray-900 mb-2">确认计算</h3>
                <p class="text-gray-600 mb-6">暂不支持标注的工时计算，点击确定继续，取消退出。</p>
                <div class="flex justify-center space-x-4">
                    <button id="cancelBtn" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-all duration-300">
                        取消
                    </button>
                    <button id="confirmBtn" class="btn-primary">
                        确定
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 结果提示框（共用） -->
    <div id="resultToast" class="fixed bottom-6 right-6 bg-white rounded-lg shadow-lg p-4 transform translate-y-20 opacity-0 transition-all duration-500 flex items-center z-50 max-w-xs">
        <div id="toastIcon" class="mr-3 text-xl"></div>
        <div>
            <p id="toastMessage" class="text-sm font-medium"></p>
        </div>
    </div>

{% endblock %}

<!-- 子页面专属脚本 -->
{% block extra_js %}
    <script>
        // 初始化效率仪表盘图表
        const ctx = document.getElementById('efficiencyChart').getContext('2d');
        let efficiencyChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                datasets: [{
                    data: [0, 100],
                    backgroundColor: [
                        '#E5E7EB', // 灰色背景
                        'rgba(0, 0, 0, 0)' // 透明
                    ],
                    borderWidth: 0,
                    cutout: '75%'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: { display: false },
                    tooltip: { enabled: false }
                },
                animation: {
                    animateRotate: true,
                    animateScale: true
                }
            }
        });

        // 文件选择事件
        document.getElementById('file').addEventListener('change', function(e) {
            const file = e.target.files[0];
            const fileInfoContainer = document.getElementById('file-info-container');
            const fileNameElement = document.getElementById('file-name');
            const fileIcon = document.getElementById('file-icon');

            if (file) {
                // 根据文件类型显示不同图标
                if (file.name.endsWith('.csv')) {
                    fileIcon.className = 'fa fa-file-text-o text-primary text-xl mr-3';
                } else if (file.name.endsWith('.xlsx') || file.name.endsWith('.xls')) {
                    fileIcon.className = 'fa fa-file-excel-o text-green-600 text-xl mr-3';
                }

                // 显示文件信息
                const fileName = file.name;
                const fileSize = (file.size / (1024 * 1024)).toFixed(2);
                fileNameElement.textContent = `${fileName} (${fileSize} MB)`;
                fileInfoContainer.classList.remove('hidden');
            } else {
                fileInfoContainer.classList.add('hidden');
            }
        });

        // 删除文件事件
        document.getElementById('delete-file').addEventListener('click', function() {
            const fileInput = document.getElementById('file');
            const fileInfoContainer = document.getElementById('file-info-container');

            fileInput.value = '';
            fileInfoContainer.classList.add('hidden');
            fileInput.dispatchEvent(new Event('change'));
        });

        // 工时输入框回车切换功能
        document.getElementById('regularHours').addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault(); // 阻止表单提交
                document.getElementById('overtimeHours').focus();
            }
        });

        document.getElementById('overtimeHours').addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault(); // 阻止表单提交
                document.getElementById('nonProductionHours').focus();
            }
        });

        document.getElementById('nonProductionHours').addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault(); // 阻止表单提交
                // 最后一个输入框按回车可以触发表单提交检查
                document.getElementById('efficiencyForm').dispatchEvent(new Event('submit'));
            }
        });

        // 表单提交事件
        document.getElementById('efficiencyForm').addEventListener('submit', function(e) {
            e.preventDefault();

            // 空值检查
            const file = document.getElementById('file').value;
            const regularHours = document.getElementById('regularHours').value;
            const overtimeHours = document.getElementById('overtimeHours').value;
            const nonProductionHours = document.getElementById('nonProductionHours').value;

            if (!file) {
                showToast('请选择上传文件', 'error');
                return;
            }

            if (!regularHours || !overtimeHours || !nonProductionHours) {
                showToast('请填写所有工时字段', 'error');
                return;
            }

            // 显示确认对话框
            const confirmDialog = document.getElementById('confirmDialog');
            const dialogContent = document.getElementById('dialogContent');
            confirmDialog.classList.remove('hidden');

            setTimeout(() => {
                dialogContent.classList.remove('scale-95', 'opacity-0');
                dialogContent.classList.add('scale-100', 'opacity-100');
            }, 10);
        });

        // 提交表单（子页面专属逻辑）
        function submitForm() {
            const formData = new FormData();
            formData.append('file', document.getElementById('file').files[0]);
            formData.append('regularHours', document.getElementById('regularHours').value);
            formData.append('overtimeHours', document.getElementById('overtimeHours').value);
            formData.append('nonProductionHours', document.getElementById('nonProductionHours').value);

            // 显示加载状态
            const submitBtn = document.getElementById('submitBtn');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>计算中...';

            fetch('/calculate', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fa fa-calculator mr-2"></i>计算效率';

                if (data.error) {
                    showToast(data.error, 'error');
                } else {
                    updateDashboard(data);
                    showToast('计算成功', 'success');
                }
            })
            .catch(error => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fa fa-calculator mr-2"></i>计算效率';
                showToast('网络错误，请重试', 'error');
                console.error('Error:', error);
            });
        }

        // 更新仪表盘数据（子页面专属逻辑）
        function updateDashboard(data) {
            const efficiency = parseFloat(data.efficiency) * 100;
            let color;

            if (efficiency < 75) {
                color = '#EF4444'; // 红色
            } else if (efficiency >= 75 && efficiency < 85) {
                color = '#F59E0B'; // 黄色
            } else {
                color = '#10B981'; // 绿色
            }

            efficiencyChart.data.datasets[0].data = [efficiency, 100 - efficiency];
            efficiencyChart.data.datasets[0].backgroundColor = [color, '#E5E7EB'];
            efficiencyChart.update();

            // 更新所有数据
            document.getElementById('efficiencyPercentage').textContent = data.efficiency_percentage;
            document.getElementById('qualifiedHours').textContent = `${data.qualified_hours} 小时`;
            document.getElementById('totalHours').textContent = `${data.total_hours} 小时`;
            document.getElementById('totalWorkingHours').textContent = `${data.total_working_hours} 小时`;
            document.getElementById('frameRate').textContent = data.frame_rate;
            document.getElementById('totalElement').textContent = data.total_element;
        }

        // 显示提示框（共用）
        function showToast(message, type) {
            const toast = document.getElementById('resultToast');
            const toastIcon = document.getElementById('toastIcon');
            const toastMessage = document.getElementById('toastMessage');

            if (type === 'success') {
                toastIcon.className = 'fa fa-check-circle text-green-500 mr-3 text-xl';
                toast.classList.remove('bg-red-50', 'border-red-500');
                toast.classList.add('bg-green-50', 'border-l-4', 'border-green-500');
            } else {
                toastIcon.className = 'fa fa-exclamation-circle text-red-500 mr-3 text-xl';
                toast.classList.remove('bg-green-50', 'border-green-500');
                toast.classList.add('bg-red-50', 'border-l-4', 'border-red-500');
            }

            toastMessage.textContent = message;
            toast.classList.remove('translate-y-20', 'opacity-0');
            toast.classList.add('translate-y-0', 'opacity-100');

            setTimeout(() => {
                toast.classList.remove('translate-y-0', 'opacity-100');
                toast.classList.add('translate-y-20', 'opacity-0');
            }, 3000);
        }

        // 关闭对话框（共用）
        function closeDialog() {
            const confirmDialog = document.getElementById('confirmDialog');
            const dialogContent = document.getElementById('dialogContent');

            dialogContent.classList.remove('scale-100', 'opacity-100');
            dialogContent.classList.add('scale-95', 'opacity-0');

            setTimeout(() => {
                confirmDialog.classList.add('hidden');
            }, 300);
        }

        // 对话框按钮事件（共用）
        document.getElementById('cancelBtn').addEventListener('click', closeDialog);
        document.getElementById('confirmBtn').addEventListener('click', function() {
            closeDialog();
            if (typeof submitForm === 'function') {
                submitForm(); // 调用子页面的提交函数
            }
        });

    </script>
{% endblock %}